package com.whf.android.jar.net.callback;

import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.GsonUtils;
import com.whf.android.jar.app.Latte;
import com.whf.android.jar.util.log.LatteLogger;

import java.io.IOException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 网络回调
 *
 * @author 傅令杰
 * @version 20.17.4.2
 */
public final class RequestCallbacks implements Callback<Object> {

    private final boolean JSON;
    private final IRequest REQUEST;
    private final ISuccess SUCCESS;
    private final IFailure FAILURE;
    private final IError ERROR;

    public RequestCallbacks(boolean json, IRequest request, ISuccess success, IFailure failure, IError error) {
        this.JSON = json;
        this.REQUEST = request;
        this.SUCCESS = success;
        this.FAILURE = failure;
        this.ERROR = error;
    }

    @Override
    public void onResponse(@NonNull Call<Object> call, @NonNull Response<Object> response) {
        if (response.isSuccessful()) {
            if (call.isExecuted() && response.body() != null) {
                final String res = GsonUtils.toJson(response.body());
                //是否需要解析；默认为不需要
                if (JSON) {
                    LatteLogger.json(res);
                    final int code = Latte.getCode(res);
                    if (Latte.getCode() == code) {
                        if (SUCCESS != null) {
                            SUCCESS.onSuccess(Latte.getData(res));
                        }
                    } else {
                        if (ERROR != null) {
                            ERROR.onError(code, Latte.getMessage(res));
                        }
                    }
                } else {
                    if (SUCCESS != null) {
                        SUCCESS.onSuccess(res);
                    }
                }
            }
        } else {
            String message = response.message();
            if (TextUtils.isEmpty(message)) {
                try {
                    message = Latte.getMessage(response.errorBody().string());
                    LatteLogger.json(message);
                } catch (IOException e) {
                    message = e.getMessage();
                }
            }
            if (ERROR != null) {
                ERROR.onError(response.code(), message);
            }
        }

    }

    @Override
    public void onFailure(@NonNull Call<Object> call, @NonNull Throwable t) {
        if (FAILURE != null) {
            FAILURE.onFailure();
        }
        if (REQUEST != null) {
            REQUEST.onRequestEnd();
        }
        if (t != null) {
            t.printStackTrace();
        }
    }

}
